package com.wetool.controller.invoicing;

import java.security.Principal;
import javax.validation.Valid;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.wetool.common.commodity.CommodityResult;
import com.wetool.common.model.Message;
import com.wetool.entity.invoicing.InventoryRecord;
import com.wetool.exception.ParamCheckException;
import com.wetool.exception.invoicing.PlacingNotFindException;
import com.wetool.exception.invoicing.ShopNotLoginException;
import com.wetool.model.enums.OutOfStorage;
import com.wetool.model.invoicing.InventoryRecordAdd;
import com.wetool.model.invoicing.InventoryRecordModify;
import com.wetool.model.invoicing.SearchParam;
import com.wetool.service.invoicing.InventoryService;
import com.wetool.service.invoicing.PlacingService;
import com.wetool.service.invoicing.SalePlacingService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

/**
 * 描述：出库控制器
 * @author lixin
 */
@RestController
@RequestMapping(value = "/placings")
@RefreshScope
@Api(description = "出库信息管理")
public class PlacingController {
	private static final Logger logger = LogManager.getLogger(InvoicingCommodityController.class);

	@Autowired
	private PlacingService placingService;
	
	@Autowired
	private InventoryService inventoryService;
	
	@Autowired
	private SalePlacingService salePlacingService;

	@ApiOperation(value="出库信息列表", notes="查询已登录店铺的出库列表", response = Message.class)
	@ApiImplicitParam(name = "shopId", value = "店铺id", required = true, dataType = "Long", paramType = "query", defaultValue = "1")
	@ApiImplicitParams({
    	@ApiImplicitParam(name = "page", value = "第几页", required = false, dataType = "int", paramType = "query", defaultValue = "0"),
    	@ApiImplicitParam(name = "size", value = "每页行数", required = false, dataType = "int", paramType = "query", defaultValue = "20"),
    	@ApiImplicitParam(name = "sort", value = "排序规则", required = false, dataType = "String", paramType = "query", defaultValue = "createDate,asc")
    })
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 6,message = "未找到出库记录!"),
			@ApiResponse(code = 14,message = "店家未登录！")
	})
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ResponseEntity<?> list(Principal principal, SearchParam searchParam, Pageable p,Long shopId,
			PagedResourcesAssembler<InventoryRecord> assembler) throws PlacingNotFindException, ShopNotLoginException {
		logger.info("进入接口>出库信息列表 . 参数：店铺ID【{}】,查询参数【{}】",shopId,searchParam);
		searchParam.setShopId(shopId);
		searchParam.setOutOfStorage(OutOfStorage.PLACING);
		/* 根据查询条件查询数据 */
		Page<InventoryRecord> page = inventoryService.findAll(searchParam, p);
		logger.info("结束接口>出库信息列表 ");
		return new ResponseEntity<>(new Message<>(CommodityResult.SUCCESS,assembler.toResource(page)), HttpStatus.OK);
	}
	
	@ApiOperation(value="查询出库信息", notes="已登录店铺的查询出库信息", response = Message.class)
	@ApiImplicitParams({
		@ApiImplicitParam(name = "shopId", value = "店铺id", required = true, dataType = "Long", paramType = "query", defaultValue = "1"),
		@ApiImplicitParam(name = "id", value = "出库单Id", required = true, dataType = "Long", paramType = "path", defaultValue = "1")
		})
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 7, message = "未找到入库记录!"),
			@ApiResponse(code = 14,message = "店家未登录！")
	})
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public ResponseEntity<?> getById(Principal principal, @PathVariable Long id,Long shopId)
			throws PlacingNotFindException, ShopNotLoginException {
		logger.info("进入接口>查询出库信息 . 参数：店铺ID【{}】,出库记录ID【{}】",shopId,id);
		if (shopId == null) {
			logger.debug("查询出库信息-> 店铺ID为空");
			throw new ShopNotLoginException();
		}
		Message<InventoryRecordModify> message = inventoryService.findOne(id);
		logger.info("结束接口>查询出库修改信息对象 ");
		return ResponseEntity.ok(message);
	}
	
	@ApiOperation(value="出库信息添加", notes="已登录店铺的添加入库信息", response = Message.class)
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 5, message = "商品不存在！"),
			@ApiResponse(code = 8, message = "添加出库信息失败!"),
			@ApiResponse(code = 14,message = "店家未登录！")
	})
	@RequestMapping(method = RequestMethod.POST)
	public ResponseEntity<?> createAddPlacing(Principal principal, @Valid @RequestBody InventoryRecordAdd inventoryRecordAdd,
			BindingResult bindingResult) throws Exception  {
		logger.info("进入接口>出库信息添加 . 参数：出库信息添加对象【{}】",inventoryRecordAdd);
		if (bindingResult.hasErrors()) {
			logger.debug("出库信息添加 . 参数格式不正确");
			throw new ParamCheckException(bindingResult);
		}
		Message<?> message = placingService.save(inventoryRecordAdd);
		logger.info("结束接口>出库信息添加");
		return ResponseEntity.ok(message);
	}
	
	@ApiOperation(value="添加出库信息", notes="已登录的店铺添加出库信息", response = Message.class)
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 2, message = "库存不足！"),
			@ApiResponse(code = 5, message = "商品不存在！"),
			@ApiResponse(code = 8, message = "添加出库信息失败!"),
			@ApiResponse(code = 9, message = "添加入库信息失败!"),
			@ApiResponse(code = 12, message = "单据已提交！"),
			@ApiResponse(code = 14,message = "店家未登录！")
	})
	@RequestMapping(value = "/addSalePlacing", method = RequestMethod.POST)
	public ResponseEntity<?> createSalePlacing(Principal principal, @Valid @RequestBody InventoryRecordAdd inventoryRecordAdd,
			BindingResult bindingResult) throws Exception {
		logger.info("进入接口>添加出库信息 . 参数：出库信息添加对象【{}】",inventoryRecordAdd);
		if (bindingResult.hasErrors()) {
			logger.debug("出库信息添加 . 参数格式不正确");
			throw new ParamCheckException(bindingResult);
		}
		salePlacingService.saveSalePlacing(inventoryRecordAdd);
		logger.info("结束接口>添加出库信息");
		return new ResponseEntity<Object>(new Message<>(CommodityResult.SUCCESS), HttpStatus.OK);
	}

	@ApiOperation(value="修改出库信息", notes="已登录店铺的修改出库信息", response = Message.class)
	@ApiImplicitParam(name = "id", value = "出库单Id", required = true, dataType = "Long", paramType = "path", defaultValue = "1")
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 5, message = "未找到商品信息！"),
			@ApiResponse(code = 12, message = "单据已提交！"),
			@ApiResponse(code = 17, message = "出库信息修改失败！"),
			@ApiResponse(code = 14,message = "店家未登录！")
	})
	@RequestMapping(value = "/{id}", method = RequestMethod.PATCH)
	public ResponseEntity<?> update(Principal principal,@PathVariable Long id,@RequestBody InventoryRecordModify inventoryRecordModify)
			throws Exception {
		logger.info("进入接口>修改出库信息 . 参数：出库信息修改对象【{}】，出库修改对象ID【{}】",inventoryRecordModify,id);
		placingService.update(id, inventoryRecordModify);
		logger.info("结束接口>修改出库信息");
		return new ResponseEntity<>(new Message<>(CommodityResult.SUCCESS), HttpStatus.OK);
	}

	@ApiOperation(value="删除出库信息", notes="已登录店铺的删除出库信息", response = Message.class)
	@ApiImplicitParams({
		@ApiImplicitParam(name = "shopId", value = "店铺id", required = true, dataType = "Long", paramType = "query", defaultValue = "1"),
		@ApiImplicitParam(name = "id", value = "出库单Id", required = true, dataType = "Long", paramType = "path", defaultValue = "1")
		})
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 12, message = "单据已提交！")
	})
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public ResponseEntity<?> delete(Principal principal, @PathVariable Long id,Long shopId) throws Exception {
		logger.info("进入接口>删除出库信息 . 参数：出库信息id【{}】，店铺ID【{}】",id,shopId);
		if (shopId == null) {
			logger.debug("删除出库信息 店铺ID为空");
			throw new ShopNotLoginException();
		}
		Message<?> message = inventoryService.delete(id);
		logger.info("结束接口>删除出库信息 ");
		return ResponseEntity.ok(message);
	}
}
